package org.jeecg.common.util;

import org.jeecg.common.exception.JeecgBootException;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class ExcelUtil {
    public static  <T> List<T>  importExcel(HttpServletRequest request, Class <T> clazz) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        List<T> list = new ArrayList<>();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            //获取文件全名
            //file.getOriginalFilename();
            int begin = file.getOriginalFilename().lastIndexOf(".");
            if(begin == -1){
                throw new JeecgBootException("文件格式不正确,请上传数据表格文件");
            }
            //获得文件后缀名
            String fileType = file.getOriginalFilename().substring(begin).toLowerCase();
            if (!fileType.endsWith(".xlsx") && !fileType.endsWith(".xls") ) {
                throw new JeecgBootException("文件格式不正确,请上传数据表格文件");
            }

            ImportParams params = new ImportParams();
            params.setNeedSave(true);
            try {
                list = ExcelImportUtil.importExcel(file.getInputStream(), clazz, params);
                return list;
            } catch (Exception e) {
                throw new JeecgBootException("文件导入失败:"+ e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return list;
    }

}
